import json

from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods

from resource.models import Resource
# 处理植被生态区数据 ============================================
from .models import VegetationEcologicalZone


# Create your views here.


# 获取数据列表
@require_http_methods(["GET"])
def vegetationEcologicalZoneList(request):
    response = {}
    try:
        items = VegetationEcologicalZone.objects.all()
        item_list = []

        for item in items:
            resources = Resource.objects.all().filter(vegetation_ecological_zone=item)
            item_list.append({
                'id': item.id,
                'name': item.name,
                'description': item.description,
                'status': item.status,
                'resource_count': len(resources)  # 计算关联的资源数量
            })
        response['msg'] = 'Get vegetation ecological zone list success!'
        response['code'] = 200
        response['data'] = item_list
    except Exception as e:
        response['msg'] = str(e)
        response['code'] = 500
    return JsonResponse(response)


# 新增
@csrf_exempt
@require_http_methods(["GET", "POST"])
def vegetationEcologicalZoneAdd(request):
    response = {}
    item = VegetationEcologicalZone()
    try:
        data = None
        if request.method == 'POST':
            # 根据Content-Type解析数据
            if request.content_type == 'application/json':
                data = json.loads(request.body)
            else:
                data = request.POST
        elif request.method == 'GET':
            data = request.GET

        # 新增判断起源是否已存在
        if VegetationEcologicalZone.objects.filter(name=data.get('name')).exists():
            response['msg'] = '该植被生态区已存在！'
            response['code'] = 500
            return JsonResponse(response)

        item.name = data.get('name')
        item.description = data.get('description')

        item.save()
        response['msg'] = '添加成功！'
        response['code'] = 200

    except Exception as e:
        response['msg'] = str(e)
        response['code'] = 500
        print('Exception')
    return JsonResponse(response)


# 修改
@csrf_exempt
@require_http_methods(["GET", "POST"])
def vegetationEcologicalZoneUpdate(request):
    response = {}
    try:
        data = None
        if request.method == 'POST':
            # 根据Content-Type解析数据
            if request.content_type == 'application/json':
                data = json.loads(request.body)
            else:
                data = request.POST
        elif request.method == 'GET':
            data = request.GET

        # 判断植被生态区是否已存在
        if VegetationEcologicalZone.objects.filter(id=data.get('id')).exists():
            item = VegetationEcologicalZone.objects.get(id=data.get('id'))
            item.name = data.get('name')
            item.description = data.get('description')
            item.status = True if data.get('status').lower() == "true" else False

            item.save(update_fields=['name', 'description', 'status'])  # 只更新指定字段
            response['msg'] = '更新成功！'
            response['code'] = 200
        else:
            response['msg'] = '该植被生态区已经不存在！'
            response['code'] = 500
            return JsonResponse(response)

    except Exception as e:
        response['msg'] = str(e)
        response['code'] = 500
        print('Exception')
    return JsonResponse(response)


# 删除
@require_http_methods(["GET", "POST"])
def vegetationEcologicalZoneDelete(request):
    response = {}
    try:
        del_id = None
        if request.method == 'GET':
            del_id = request.GET.get('id')
        elif request.method == 'POST':
            del_id = request.POST.get('id')

        if not del_id:
            response['msg'] = 'The ID is required!'
            response['code'] = 500
            return JsonResponse(response)

        item = VegetationEcologicalZone.objects.get(id=del_id)
        item.delete()
        response['msg'] = 'Vegetation ecological zone deleted successfully!'
        response['code'] = 200
    except VegetationEcologicalZone.DoesNotExist:
        response['msg'] = 'Vegetation ecological zone not found!'
        response['code'] = 500
    except Exception as e:
        response['msg'] = str(e)
        response['code'] = 500
    return JsonResponse(response)


# 处理生态工程区数据 ============================================
from .models import EcologicalEngineeringZone


# 获取数据列表
@require_http_methods(["GET"])
def ecologicalEngineeringZoneList(request):
    response = {}
    try:
        items = EcologicalEngineeringZone.objects.all()
        item_list = []

        for item in items:
            resources = Resource.objects.all().filter(ecological_engineering_zone=item)
            item_list.append({
                'id': item.id,
                'name': item.name,
                'description': item.description,
                'status': item.status,
                'resource_count': len(resources)  # 计算关联的资源数量
            })
        response['msg'] = 'Get ecological engineering zone list success!'
        response['code'] = 200
        response['data'] = item_list
    except Exception as e:
        response['msg'] = str(e)
        response['code'] = 500
    return JsonResponse(response)


# 新增
@csrf_exempt
@require_http_methods(["GET", "POST"])
def ecologicalEngineeringZoneAdd(request):
    response = {}
    item = EcologicalEngineeringZone()
    try:
        data = None
        if request.method == 'POST':
            # 根据Content-Type解析数据
            if request.content_type == 'application/json':
                data = json.loads(request.body)
            else:
                data = request.POST
        elif request.method == 'GET':
            data = request.GET

        # 新增判断起源是否已存在
        if EcologicalEngineeringZone.objects.filter(name=data.get('name')).exists():
            response['msg'] = '该生态工程区已存在！'
            response['code'] = 500
            return JsonResponse(response)

        item.name = data.get('name')
        item.description = data.get('description')

        item.save()
        response['msg'] = '添加成功！'
        response['code'] = 200

    except Exception as e:
        response['msg'] = str(e)
        response['code'] = 500
        print('Exception')
    return JsonResponse(response)


# 修改
@csrf_exempt
@require_http_methods(["GET", "POST"])
def ecologicalEngineeringZoneUpdate(request):
    response = {}
    try:
        data = None
        if request.method == 'POST':
            # 根据Content-Type解析数据
            if request.content_type == 'application/json':
                data = json.loads(request.body)
            else:
                data = request.POST
        elif request.method == 'GET':
            data = request.GET

        # 判断生态工程区是否已存在
        if EcologicalEngineeringZone.objects.filter(id=data.get('id')).exists():
            item = EcologicalEngineeringZone.objects.get(id=data.get('id'))
            item.name = data.get('name')
            item.description = data.get('description')
            item.status = True if data.get('status').lower() == "true" else False

            item.save(update_fields=['name', 'description', 'status'])  # 只更新指定字段
            response['msg'] = '更新成功！'
            response['code'] = 200
        else:
            response['msg'] = '该生态工程区已经不存在！'
            response['code'] = 500
            return JsonResponse(response)

    except Exception as e:
        response['msg'] = str(e)
        response['code'] = 500
        print('Exception')
    return JsonResponse(response)


# 删除
@require_http_methods(["GET", "POST"])
def ecologicalEngineeringZoneDelete(request):
    response = {}
    try:
        del_id = None
        if request.method == 'GET':
            del_id = request.GET.get('id')
        elif request.method == 'POST':
            del_id = request.POST.get('id')

        if not del_id:
            response['msg'] = 'The ID is required!'
            response['code'] = 500
            return JsonResponse(response)

        item = EcologicalEngineeringZone.objects.get(id=del_id)
        item.delete()
        response['msg'] = 'Ecological engineering zone deleted successfully!'
        response['code'] = 200
    except EcologicalEngineeringZone.DoesNotExist:
        response['msg'] = 'Ecological engineering zone not found!'
        response['code'] = 500
    except Exception as e:
        response['msg'] = str(e)
        response['code'] = 500
    return JsonResponse(response)


# 处理森林类别数据 ============================================
from .models import ForestClass


# 获取数据列表
@require_http_methods(["GET"])
def forestClassList(request):
    response = {}
    try:
        items = ForestClass.objects.all()
        item_list = []

        for item in items:
            resources = Resource.objects.all().filter(forest_class=item)
            item_list.append({
                'id': item.id,
                'name': item.name,
                'level': item.level,
                'description': item.description,
                'status': item.status,
                'resource_count': len(resources)  # 计算关联的资源数量
            })
        response['msg'] = 'Get forest class list success!'
        response['code'] = 200
        response['data'] = item_list
    except Exception as e:
        response['msg'] = str(e)
        response['code'] = 500
    return JsonResponse(response)


# 新增
@csrf_exempt
@require_http_methods(["GET", "POST"])
def forestClassAdd(request):
    response = {}

    try:
        data = None
        if request.method == 'POST':
            # 根据Content-Type解析数据
            if request.content_type == 'application/json':
                data = json.loads(request.body)
            else:
                data = request.POST
        elif request.method == 'GET':
            data = request.GET

        # 新增判断角色是否已存在
        if ForestClass.objects.filter(name=data.get('name'), level=data.get('level')).exists():
            response['msg'] = '该森林类别已存在！'
            response['code'] = 500
            return JsonResponse(response)

        # 创建新的森林类别对象
        item = ForestClass()
        item.name = data.get('name')
        item.level = data.get('level')
        item.description = data.get('description')

        item.save()
        response['msg'] = '添加成功！'
        response['code'] = 200

    except Exception as e:
        response['msg'] = str(e)
        response['code'] = 500
        print('Exception')
    return JsonResponse(response)


# 修改
@csrf_exempt
@require_http_methods(["GET", "POST"])
def forestClassUpdate(request):
    response = {}
    try:
        data = None
        if request.method == 'POST':
            # 根据Content-Type解析数据
            if request.content_type == 'application/json':
                data = json.loads(request.body)
            else:
                data = request.POST
        elif request.method == 'GET':
            data = request.GET

        # 判断森林类别是否已存在
        if ForestClass.objects.filter(id=data.get('id')).exists():
            item = ForestClass.objects.get(id=data.get('id'))
            item.name = data.get('name', item.name)
            item.level = data.get('level', item.level)
            item.description = data.get('description', item.description)
            item.status = True if data.get('status').lower() == "true" else False

            item.save(update_fields=['name', 'level', 'description', 'status'])  # 只更新指定字段
            response['msg'] = '更新成功！'
            response['code'] = 200
        else:
            response['msg'] = '该森林类别不存在！'
            response['code'] = 500
            return JsonResponse(response)

    except Exception as e:
        response['msg'] = str(e)
        response['code'] = 500
        print('Exception')
    return JsonResponse(response)


# 删除
@require_http_methods(["GET", "POST"])
def forestClassDelete(request):
    response = {}
    try:
        del_id = None
        if request.method == 'GET':
            del_id = request.GET.get('id')
        elif request.method == 'POST':
            del_id = request.POST.get('id')

        if not del_id:
            response['msg'] = 'The ID is required!'
            response['code'] = 500
            return JsonResponse(response)

        item = ForestClass.objects.get(id=del_id)
        item.delete()
        response['msg'] = 'Forest class deleted successfully!'
        response['code'] = 200
    except ForestClass.DoesNotExist:
        response['msg'] = 'Forest class not found!'
        response['code'] = 500
    except Exception as e:
        response['msg'] = str(e)
        response['code'] = 500
    return JsonResponse(response)


# 处理生态分区数据 ============================================
from .models import EcologicalZone


# 获取数据列表
@require_http_methods(["GET"])
def ecologicalZoneList(request):
    response = {}
    try:
        items = EcologicalZone.objects.all()
        item_list = []

        for item in items:
            resources = Resource.objects.all().filter(ecological_zone=item)
            item_list.append({
                'id': item.id,
                'name': item.name,
                'description': item.description,
                'status': item.status,
                'resource_count': len(resources)  # 计算关联的资源数量
            })
        response['msg'] = 'Get ecological zone list success!'
        response['code'] = 200
        response['data'] = item_list
    except Exception as e:
        response['msg'] = str(e)
        response['code'] = 500
    return JsonResponse(response)


# 新增
@csrf_exempt
@require_http_methods(["GET", "POST"])
def ecologicalZoneAdd(request):
    response = {}
    item = EcologicalZone()
    try:
        data = None
        if request.method == 'POST':
            # 根据Content-Type解析数据
            if request.content_type == 'application/json':
                data = json.loads(request.body)
            else:
                data = request.POST
        elif request.method == 'GET':
            data = request.GET

        # 新增判断角色是否已存在
        if EcologicalZone.objects.filter(name=data.get('name')).exists():
            response['msg'] = '该森林类别已存在！'
            response['code'] = 500
            return JsonResponse(response)

        item.name = data.get('name')
        item.description = data.get('description')

        item.save()
        response['msg'] = '添加成功！'
        response['code'] = 200

    except Exception as e:
        response['msg'] = str(e)
        response['code'] = 500
        print('Exception')
    return JsonResponse(response)


# 修改
@csrf_exempt
@require_http_methods(["GET", "POST"])
def ecologicalZoneUpdate(request):
    response = {}
    try:
        data = None
        if request.method == 'POST':
            # 根据Content-Type解析数据
            if request.content_type == 'application/json':
                data = json.loads(request.body)
            else:
                data = request.POST
        elif request.method == 'GET':
            data = request.GET

        # 判断生态分区是否已存在
        if EcologicalZone.objects.filter(id=data.get('id')).exists():
            item = EcologicalZone.objects.get(id=data.get('id'))
            item.name = data.get('name')
            item.description = data.get('description')
            item.status = True if data.get('status').lower() == "true" else False

            item.save(update_fields=['name', 'description', 'status'])  # 只更新指定字段
            response['msg'] = '更新成功！'
            response['code'] = 200
        else:
            response['msg'] = '该分区不存在！'
            response['code'] = 500
            return JsonResponse(response)

    except Exception as e:
        response['msg'] = str(e)
        response['code'] = 500
        print('Exception')
    return JsonResponse(response)


# 删除
@require_http_methods(["GET", "POST"])
def ecologicalZoneDelete(request):
    response = {}
    try:
        del_id = None
        if request.method == 'GET':
            del_id = request.GET.get('id')
        elif request.method == 'POST':
            del_id = request.POST.get('id')

        if not del_id:
            response['msg'] = 'The ID is required!'
            response['code'] = 500
            return JsonResponse(response)

        item = EcologicalZone.objects.get(id=del_id)
        item.delete()
        response['msg'] = 'Ecological zone deleted successfully!'
        response['code'] = 200
    except EcologicalZone.DoesNotExist:
        response['msg'] = 'Ecological zone not found!'
        response['code'] = 500
    except Exception as e:
        response['msg'] = str(e)
        response['code'] = 500
    return JsonResponse(response)


# 处理树种数据 ============================================
from .models import TreeSpecies


# 获取数据列表
@require_http_methods(["GET"])
def treeSpeciesList(request):
    response = {}
    try:
        items = TreeSpecies.objects.all()
        item_list = []

        for item in items:
            resources = Resource.objects.all().filter(dominant_tree_species=item)
            item_list.append({
                'id': item.id,
                'name': item.name,
                'description': item.description,
                'status': item.status,
                'resource_count': len(resources)  # 计算关联的资源数量
            })
        response['msg'] = 'Get tree species list success!'
        response['code'] = 200
        response['data'] = item_list
    except Exception as e:
        response['msg'] = str(e)
        response['code'] = 500
    return JsonResponse(response)


# 新增
@csrf_exempt
@require_http_methods(["GET", "POST"])
def treeSpeciesAdd(request):
    response = {}
    item = TreeSpecies()
    try:
        data = None
        if request.method == 'POST':
            # 根据Content-Type解析数据
            if request.content_type == 'application/json':
                data = json.loads(request.body)
            else:
                data = request.POST
        elif request.method == 'GET':
            data = request.GET

        # 新增判断角色是否已存在
        if TreeSpecies.objects.filter(name=data.get('name')).exists():
            response['msg'] = '该树种已存在！'
            response['code'] = 500
            return JsonResponse(response)

        item.name = data.get('name')
        item.description = data.get('description')

        item.save()
        response['msg'] = '添加成功！'
        response['code'] = 200

    except Exception as e:
        response['msg'] = str(e)
        response['code'] = 500
        print('Exception')
    return JsonResponse(response)


# 修改
@csrf_exempt
@require_http_methods(["GET", "POST"])
def treeSpeciesUpdate(request):
    response = {}
    try:
        data = None
        if request.method == 'POST':
            # 根据Content-Type解析数据
            if request.content_type == 'application/json':
                data = json.loads(request.body)
            else:
                data = request.POST
        elif request.method == 'GET':
            data = request.GET

        # 判断树种是否已存在
        if TreeSpecies.objects.filter(id=data.get('id')).exists():
            item = TreeSpecies.objects.get(id=data.get('id'))
            item.name = data.get('name')
            item.description = data.get('description')
            item.status = True if data.get('status').lower() == "true" else False

            item.save(update_fields=['name', 'description', 'status'])  # 只更新指定字段
            response['msg'] = '更新成功！'
            response['code'] = 200
        else:
            response['msg'] = '该树种不存在！'
            response['code'] = 500
            return JsonResponse(response)

    except Exception as e:
        response['msg'] = str(e)
        response['code'] = 500
        print('Exception')
    return JsonResponse(response)


# 删除
@require_http_methods(["GET", "POST"])
def treeSpeciesDelete(request):
    response = {}
    try:
        del_id = None
        if request.method == 'GET':
            del_id = request.GET.get('id')
        elif request.method == 'POST':
            del_id = request.POST.get('id')

        if not del_id:
            response['msg'] = 'The ID is required!'
            response['code'] = 500
            return JsonResponse(response)

        item = TreeSpecies.objects.get(id=del_id)
        item.delete()
        response['msg'] = 'Tree species deleted successfully!'
        response['code'] = 200
    except TreeSpecies.DoesNotExist:
        response['msg'] = 'Tree species not found!'
        response['code'] = 500
    except Exception as e:
        response['msg'] = str(e)
        response['code'] = 500
    return JsonResponse(response)


# 处理起源数据 ============================================
from .models import Origin


# 获取数据列表
@require_http_methods(["GET"])
def originList(request):
    response = {}
    try:
        items = Origin.objects.all()
        item_list = []

        for item in items:
            resources = Resource.objects.all().filter(origin=item)
            item_list.append({
                'id': item.id,
                'name': item.name,
                'description': item.description,
                'status': item.status,
                'resource_count': len(resources)  # 计算关联的资源数量
            })
        response['msg'] = 'Get origin list success!'
        response['code'] = 200
        response['data'] = item_list
    except Exception as e:
        response['msg'] = str(e)
        response['code'] = 500
    return JsonResponse(response)


# 新增
@csrf_exempt
@require_http_methods(["GET", "POST"])
def originAdd(request):
    response = {}
    item = Origin()
    try:
        data = None
        if request.method == 'POST':
            # 根据Content-Type解析数据
            if request.content_type == 'application/json':
                data = json.loads(request.body)
            else:
                data = request.POST
        elif request.method == 'GET':
            data = request.GET

        # 新增判断起源是否已存在
        if Origin.objects.filter(name=data.get('name')).exists():
            response['msg'] = '该起源已存在！'
            response['code'] = 500
            return JsonResponse(response)

        item.name = data.get('name')
        item.description = data.get('description')

        item.save()
        response['msg'] = '添加成功！'
        response['code'] = 200

    except Exception as e:
        response['msg'] = str(e)
        response['code'] = 500
        print('Exception')
    return JsonResponse(response)


# 修改
@csrf_exempt
@require_http_methods(["GET", "POST"])
def originUpdate(request):
    response = {}
    try:
        data = None
        if request.method == 'POST':
            # 根据Content-Type解析数据
            if request.content_type == 'application/json':
                data = json.loads(request.body)
            else:
                data = request.POST
        elif request.method == 'GET':
            data = request.GET

        # 判断起源是否已存在
        if Origin.objects.filter(id=data.get('id')).exists():
            item = Origin.objects.get(id=data.get('id'))
            item.name = data.get('name')
            item.description = data.get('description')
            item.status = True if data.get('status').lower() == "true" else False

            item.save(update_fields=['name', 'description', 'status'])  # 只更新指定字段
            response['msg'] = '更新成功！'
            response['code'] = 200
        else:
            response['msg'] = '该起源不存在！'
            response['code'] = 500
            return JsonResponse(response)

    except Exception as e:
        response['msg'] = str(e)
        response['code'] = 500
        print('Exception')
    return JsonResponse(response)


# 删除
@require_http_methods(["GET", "POST"])
def originDelete(request):
    response = {}
    try:
        del_id = None
        if request.method == 'GET':
            del_id = request.GET.get('id')
        elif request.method == 'POST':
            del_id = request.POST.get('id')

        if not del_id:
            response['msg'] = 'The ID is required!'
            response['code'] = 500
            return JsonResponse(response)

        origin = Origin.objects.get(id=del_id)
        origin.delete()
        response['msg'] = 'Origin deleted successfully!'
        response['code'] = 200
    except Origin.DoesNotExist:
        response['msg'] = 'Origin not found!'
        response['code'] = 500
    except Exception as e:
        response['msg'] = str(e)
        response['code'] = 500
    return JsonResponse(response)


# 处理年龄组数据 ============================================
from .models import AgeGroup


# 获取数据列表
@require_http_methods(["GET"])
def ageGroupList(request):
    response = {}
    try:
        items = AgeGroup.objects.all()
        item_list = []
        for item in items:
            resources = Resource.objects.all().filter(age_group=item)
            # print(f'@resources ({len(resources)}) for age group {item.name}: ', resources.values())
            item_list.append({
                'id': item.id,
                'name': item.name,
                'description': item.description,
                'status': item.status,
                'resource_count': len(resources)  # 计算关联的资源数量
            })
        response['msg'] = 'Get age group list success!'
        response['code'] = 200
        response['data'] = item_list
    except Exception as e:
        response['msg'] = str(e)
        response['code'] = 500
    return JsonResponse(response)


# 新增
@csrf_exempt
@require_http_methods(["GET", "POST"])
def ageGroupAdd(request):
    response = {}
    item = AgeGroup()
    try:
        data = None
        if request.method == 'POST':
            # 根据Content-Type解析数据
            if request.content_type == 'application/json':
                data = json.loads(request.body)
            else:
                data = request.POST
        elif request.method == 'GET':
            data = request.GET

        # 新增判断起源是否已存在
        if AgeGroup.objects.filter(name=data.get('name')).exists():
            response['msg'] = '该年龄组已存在！'
            response['code'] = 500
            return JsonResponse(response)

        item.name = data.get('name')
        item.description = data.get('description')

        item.save()
        response['msg'] = '添加成功！'
        response['code'] = 200

    except Exception as e:
        response['msg'] = str(e)
        response['code'] = 500
        print('Exception')
    return JsonResponse(response)


# 修改
@csrf_exempt
@require_http_methods(["GET", "POST"])
def ageGroupUpdate(request):
    response = {}
    try:
        data = None
        if request.method == 'POST':
            # 根据Content-Type解析数据
            if request.content_type == 'application/json':
                data = json.loads(request.body)
            else:
                data = request.POST
        elif request.method == 'GET':
            data = request.GET

        # 判断年龄组是否已存在
        if AgeGroup.objects.filter(id=data.get('id')).exists():
            item = AgeGroup.objects.get(id=data.get('id'))
            item.name = data.get('name')
            item.description = data.get('description')
            item.status = True if data.get('status').lower() == "true" else False

            item.save(update_fields=['name', 'description', 'status'])  # 只更新指定字段
            response['msg'] = '更新成功！'
            response['code'] = 200
        else:
            response['msg'] = '该年龄组已经不存在！'
            response['code'] = 500
            return JsonResponse(response)

    except Exception as e:
        response['msg'] = str(e)
        response['code'] = 500
        print('Exception')
    return JsonResponse(response)


# 删除
@require_http_methods(["GET", "POST"])
def ageGroupDelete(request):
    response = {}
    try:
        del_id = None
        if request.method == 'GET':
            del_id = request.GET.get('id')
        elif request.method == 'POST':
            del_id = request.POST.get('id')

        if not del_id:
            response['msg'] = 'The ID is required!'
            response['code'] = 500
            return JsonResponse(response)

        item = AgeGroup.objects.get(id=del_id)
        item.delete()
        response['msg'] = 'Age group deleted successfully!'
        response['code'] = 200
    except AgeGroup.DoesNotExist:
        response['msg'] = 'Age group not found!'
        response['code'] = 500
    except Exception as e:
        response['msg'] = str(e)
        response['code'] = 500
    return JsonResponse(response)
